package com.example.experiment4

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import androidx.core.content.ContextCompat

class CardAdapter(
    private val context: Context,
    private val cards: List<Card>,
    private val onClick: (Int) -> Unit
) : BaseAdapter() {

    override fun getCount(): Int = cards.size

    override fun getItem(position: Int): Any = cards[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val imageView = ImageView(context)
        imageView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            200 // 牌的高度，可调整
        )
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        imageView.setPadding(4, 4, 4, 4)
        imageView.setOnClickListener { onClick(position) }

        // 区分牌面和背面（用具体颜色值替代资源引用，彻底解决兼容性问题）
        if (cards[position].isFaceUp) {
            when (cards[position].identifier) {
                1 -> imageView.setBackgroundColor(0xFFFF0000.toInt()) // 红色
                2 -> imageView.setBackgroundColor(0xFFFFA500.toInt()) // 橙色
                3 -> imageView.setBackgroundColor(0xFFFFFF00.toInt()) // 黄色
                4 -> imageView.setBackgroundColor(0xFF00FF00.toInt()) // 绿色
                5 -> imageView.setBackgroundColor(0xFF0000FF.toInt()) // 蓝色
                6 -> imageView.setBackgroundColor(0xFF800080.toInt()) // 紫色
                7 -> imageView.setBackgroundColor(0xFF808080.toInt()) // 灰色
                8 -> imageView.setBackgroundColor(0xFF000000.toInt()) // 黑色
            }
        } else {
            imageView.setBackgroundColor(0xFF808080.toInt()) // 灰色（背面）
        }
        return imageView
    }
}